package se.janlindblom.ordning.android;

/**
 * $Id: OrdningActivity.java 59 2009-12-06 16:39:11Z lindblom.jan $
 * 
 * Copyright (c) 2009, Jan Lindblom
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 * 
 * * Redistributions of source code must retain the above copyright notice,
 *   this list of conditions and the following disclaimer.
 * 
 * * Redistributions in binary form must reproduce the above copyright notice,
 *   this list of conditions and the following disclaimer in the documentation
 *   and/or other materials provided with the distribution.
 * 
 * * Neither the name of the project nor the names of its contributors may be
 *   used to endorse or promote products derived from this software without
 *   specific prior written permission.
 *   
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 * 
 */

import java.util.Calendar;
import java.util.Observable;
import java.util.Observer;
import java.util.Vector;
import se.janlindblom.ordning.helper.Puls;
import se.janlindblom.ordning.typ.Id;
import se.janlindblom.ordning.typ.Kategori;
import se.janlindblom.ordning.typ.samling.Aktiviteter;
import se.janlindblom.ordning.typ.samling.Kategorier;
import android.app.Activity;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.widget.CompoundButton;
import android.widget.RadioButton;
import android.widget.RadioGroup;

/**
 * 
 * @author Jan Lindblom (lindblom.jan@gmail.com)
 * @version $Rev: 59 $
 */
public class OrdningActivity extends Activity implements Observer {
	public static final String PREFS_NAME = "Ordning";
	
	private Kategorier categories = new Kategorier();
	private Puls puls = new Puls();
	private Vector<Aktiviteter> activityCollections = new Vector<Aktiviteter>();
//	private DateFormat df = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG);
//	private DateFormat timeFormatter = DateFormat.getTimeInstance(DateFormat.LONG);
	private Handler mHandler = new Handler();
	
	private Long tick = new Long(System.currentTimeMillis());
	
	final Runnable mUpdateResults = new Runnable() {
		public void run() {
			SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
			int selectedId = settings.getInt("selection", -1);
			if (selectedId != -1) {
				Editor e = settings.edit();
				e.putLong("category" + selectedId + ".duration", (tick - settings.getLong("category" + selectedId + ".started", 0)));
				e.commit();
			}
				
			updateResultsInUi();
		}
	};
    
    private void updateResultsInUi() {
    	RadioGroup rg = (RadioGroup) findViewById(R.id.categories);
		RadioButton rb = (RadioButton) findViewById(rg.getCheckedRadioButtonId());
		if (rb != null) {
			SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
			int selectedId = settings.getInt("selection", -1);
			Calendar c = Calendar.getInstance();
			if (selectedId != -1)
				c.setTimeInMillis(settings.getLong("category" + selectedId + ".duration", 0));
//			System.err.println("category" + selectedId + ".duration=" + settings.getLong("category" + selectedId + ".duration", 0));
			if (settings.getLong("category" + selectedId + ".duration", 0) == 0)
				rb.setText(categories.get(((Integer)rb.getTag()).intValue()).getName() + ": ");
			else
				rb.setText(categories.get(((Integer)rb.getTag()).intValue()).getName() + ": " + (c.get(Calendar.DAY_OF_YEAR) - 1)
						+ " days, " + (c.get(Calendar.HOUR_OF_DAY) - 1) + " hours, " + c.get(Calendar.MINUTE) + " minutes and "
						+ c.get(Calendar.SECOND) + " seconds.");
		}
    }
	
    /**
     * 
     */
    @Override
    public void onPause() {
    	super.onPause();
    	if (puls.isRunning())
    		puls.setRunning(false);
    	System.err.println("Pausing...");
    	SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
    	int selectedId = settings.getInt("selection", -1);
		if (selectedId != -1) {
			Editor editor = settings.edit();
			editor.putLong("category" + selectedId + ".duration",
					(tick - settings.getLong("category" + selectedId + ".started", tick)));
			editor.commit();
		}
    }
    
    /**
     * 
     */
    @Override
    public void onResume() {
    	super.onResume();
    	System.err.println("Resuming...");
    	
    	SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
        int selectedCounter = settings.getInt("selection", -1);
        System.err.println("Selection: " + selectedCounter);
        if (selectedCounter != -1) {
        	RadioGroup rg = (RadioGroup) findViewById(R.id.categories);
        	((RadioButton)rg.getChildAt(selectedCounter)).setSelected(true);
        	((RadioButton)rg.getChildAt(selectedCounter)).setChecked(true);
        }
    	
    	if (!puls.isRunning())
    		puls.getThread().start();
    }
    
    /**
     * 
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        System.err.println("Created...");
        
        puls.addObserver(this);
        Thread pulsThread = puls.getThread();
        if (!puls.isRunning())
        	pulsThread.start();
        
        
        RadioGroup rg = (RadioGroup) findViewById(R.id.categories);
        
        for (int i=0;i<rg.getChildCount();i++) {
        	RadioButton rb = (RadioButton) rg.getChildAt(i);
        	Kategori k = new Kategori(new Id(i,0,0));
        	categories.add(k);
        	activityCollections.add(i, new Aktiviteter(k));
        	rb.setText(k.getName());
        	rb.setTag(new Integer(i));
			Calendar c = Calendar.getInstance();
			SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);				
			c.setTimeInMillis(settings.getLong("category" + i + ".duration", 0));
			if (settings.getLong("category" + i + ".duration", 0) == 0)
				rb.setText(categories.get(i).getName() + ": ");
			else
				rb.setText(categories.get(i).getName() + ": " + (c.get(Calendar.DAY_OF_YEAR) - 1)
						+ " days, " + (c.get(Calendar.HOUR_OF_DAY) - 1) + " hours, " + c.get(Calendar.MINUTE) + " minutes and "
						+ c.get(Calendar.SECOND) + " seconds.");
        	rb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
    			
    			@Override
    			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
    				int selectedId = ((Integer)buttonView.getTag()).intValue();
    				SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
    				Editor editor = settings.edit();
    				if (isChecked) {
    					/* I was selected. */
    					editor.putInt("selection", selectedId);
    					editor.commit();
    					editor.putLong("category" + selectedId + ".started", tick);
    					editor.commit();
    					editor.putLong("started", tick);
    					editor.commit();
    					System.err.println("SELECTED:category" + selectedId + ".duration=" + settings.getLong("category" + selectedId + ".duration", 0));
    				} else {
    					/* I was unselected! */
    					editor.putLong("category" + selectedId + ".stopped", tick);
    					editor.commit();
    					long stopped = settings.getLong("category" + selectedId + ".stopped", tick);
    					long started = settings.getLong("category" + selectedId + ".started", tick);
    					long duration = settings.getLong("category" + selectedId + ".duration", 0);
    					System.err.println("UNSELECTED:category" + selectedId + ".duration=" + settings.getLong("category" + selectedId + ".duration", 0));
    					System.err.println("UNSELECTED:stopped-started=" + (stopped - started));
    					duration += (stopped - started);
    					editor.putLong("category" + selectedId + ".duration", duration);
    					editor.commit();
    				}
    				System.err.println("DONE:category" + selectedId + ".duration=" + settings.getLong("category" + selectedId + ".duration", 0));
    			}
    		});
        }
        	
        
        
        //SQLiteDatabase.openDatabase("ordning.db", null, SQLiteDatabase.CREATE_IF_NECESSARY);
    }

    /**
     * 
     */
	@Override
	public void update(Observable arg0, Object arg1) {
		tick = (Long) arg1;
		mHandler.post(mUpdateResults);		
	}
}